package com.thinkfit.jy.utils;

import android.content.Context;

import com.common.lib.bean.BasicResponse;
import com.common.lib.bean.SportSectionBean;
import com.common.lib.constant.EventBusEvent;
import com.common.lib.manager.DataManager;
import com.common.lib.network.HttpMethods;
import com.thinkfit.jy.serialport.SerialPortManager;
import com.thinkfit.jy.serialport.SportType;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;

import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;

public class SportsDataUtils {

    ArrayList<SerialPortManager.CurrentInfo> sportsDatas;
    ArrayList<SportSectionBean> upSportsData = new ArrayList<>();
    ArrayList<Float> speeds = new ArrayList<>();//速度集
    ArrayList<Float> drag = new ArrayList<>();//阻力集
    ArrayList<Float> watts = new ArrayList<>();//设备功率集
    ArrayList<Float> reta = new ArrayList<>();//心率集
    ArrayList<Float> rpms = new ArrayList<>();//步频集
    int intervalTime = 10;
    int time = 0;
    int mRid;
    static SportsDataUtils sportsDataUtils;

    Disposable disposable;

    boolean isUpData = false;

    public SportType mSportType = SportType.FREE;  //1视频2语音3自由4实景

    public void setSportType(SportType sportType) {
        mSportType = sportType;
    }

    public static SportsDataUtils getInstance(){
        if(sportsDataUtils == null){
            sportsDataUtils = new SportsDataUtils();
        }

        return sportsDataUtils;
    }

    public void setSportsData(SerialPortManager.CurrentInfo b){
        if(sportsDatas == null){
            sportsDatas = new ArrayList<>();
        }
        if(time < b.time){
            System.out.println("ddddddddddddddddddddddd  SportsDataUtils   CurrentInfo.data :  "+b.toString());
            time = b.time;
            SerialPortManager.CurrentInfo currentInfo = new SerialPortManager.CurrentInfo();
            currentInfo.time = b.time;
            currentInfo.heart = b.heart;
            currentInfo.speed = b.speed;
            currentInfo.count = b.count;
            currentInfo.slop = b.slop;
            currentInfo.resistance = b.resistance;
            currentInfo.kcal = b.kcal;
            currentInfo.distance = b.distance;
            currentInfo.power = b.power;
            currentInfo.rpm = b.rpm;
            currentInfo.isCountChange = b.isCountChange;
            currentInfo.lastCount = b.lastCount;
            currentInfo.steps = b.steps;
            sportsDatas.add(currentInfo);

        }
    }
    int min = 0;
    public ArrayList<SportSectionBean> getSportsData(){

        System.out.println("ddddddddddddddddddddddd  SportsDataUtils   sportsData.size :  "+sportsDatas.size());
        for (int i = 0;i<sportsDatas.size();i++){
            System.out.println("ddddddddddddddddddddddd  SportsDataUtils   i : "+i +"  sportsData.toString111  :  "+sportsDatas.get(i).toString());
            speeds.add((float) sportsDatas.get(i).speed);
            drag.add((float) sportsDatas.get(i).slop);
            watts.add((float) sportsDatas.get(i).power);
            reta.add((float) sportsDatas.get(i).heart);
            rpms.add((float) sportsDatas.get(i).rpm);
            if((sportsDatas.get(i).time % intervalTime) ==0){
                System.out.println("ddddddddddddddddddddddd  SportsDataUtils   intervalTime  :  "+sportsDatas.get(i).time);
                ArrayList<Float> speedsData = speeds;
                ArrayList<Float> dragData = drag;
                ArrayList<Float> wattsData = watts;
                ArrayList<Float> retaData = reta;
                ArrayList<Float> rpmData = rpms;
                float meanSpeed = 0f;
                if(DeviceTypeUtils.getDeviceType() == 2){
                    meanSpeed = mean(speedsData)*0.1f;
                }else {
                    meanSpeed = mean(speedsData)*0.01f;
                }
                float meanDrag = mean(dragData);
                float meanWatts = mean(wattsData);
                float meanReta = mean(retaData);

                double rand = Math.random()*10;
                rand=(rand-5)*0.01+1;
                int rpm = (int) Math.ceil(meanSpeed*60/3.6*rand);
                float meanRpm = rpm;

                int minute = (sportsDatas.get(i).time / 60) % 60;
                System.out.println("ddddddddddddddddddddddd  SportsDataUtils   minute  :  "+minute);
                if(minute <= 0){
                    min = 1;
                }else {
                    min = minute+1;
                }
                SportSectionBean sportSectionBean = new SportSectionBean();
                sportSectionBean.setDrag(Math.round(meanDrag));
                sportSectionBean.setReta(Math.round(meanReta));
                sportSectionBean.setSpeed(Math.round(meanSpeed)+"");
                sportSectionBean.setWatts(Math.round(meanWatts)+"");
                sportSectionBean.setMin(min);
                sportSectionBean.setAdvrpm(Math.round(meanRpm));
                System.out.println("ddddddddddddddddddddddd  SportsDataUtils   min  :  "+min);
                System.out.println("ddddddddddddddddddddddd  SportsDataUtils   upSportsData.size  :  "+ upSportsData.size());
                if(upSportsData.size() < min){
                    upSportsData.add(sportSectionBean);//不够的时候添加
                }else {
                    upSportsData.set(min-1,sportSectionBean);//够的时候替换
                }

                clearList();
                time = 0;
            }
        }


        return upSportsData;
    }

    public void uploadSportInfo(boolean isEnd) {
        if (!DataManager.Companion.getInstance().isLogin() || sportsDatas.get(sportsDatas.size()-1).time < 10) {  //自由运动少于10秒不传
            SportsDataUtils.getInstance().setSportType(SportType.FREE);
            LoadViewUtils.getInstance().showToast();
            LoadViewUtils.getInstance().goneLayout();
            HashMap<String, Object> map = new HashMap<>();
            map.put(EventBusEvent.KILL_ACTIVITY, 0);
            EventBus.getDefault().post(map);
            return;
        }
        System.out.println("ddddddddddddddddddddddd   isUpData   : "+isUpData);
        if(isUpData){
            return;
        }
        closeDisposable();
        HashMap<String, Object> map = new HashMap<>();
        map.put(EventBusEvent.KILL_ACTIVITY, 0);
        EventBus.getDefault().post(map);
        isUpData = true;
        ArrayList<SportSectionBean> sportsData = getSportsData();
        System.out.println("ddddddddddddddddddddddd   SportsDataUtils   sportsData.size  : "+sportsData.size());

        Observer observer = new Observer<BasicResponse<Object>>() {

            @Override
            public void onSubscribe(io.reactivex.rxjava3.disposables.@NonNull Disposable d) {
                disposable = d;
            }

            @Override
            public void onNext(BasicResponse<Object> bean) {
                if (bean.isSuccess()) {
                    mRid = bean.getRid();
                    HashMap<String, Object> map = new HashMap<>();
                    map.put(EventBusEvent.SPORTS_REPORT,mRid);
                    EventBus.getDefault().post(map);
                    isUpData = false;
                }
            }

            @Override
            public void onError(Throwable e) {
                isUpData = false;
                SportsDataUtils.getInstance().setSportType(SportType.FREE);
            }

            @Override
            public void onComplete() {
                isUpData = false;
                SportsDataUtils.getInstance().setSportType(SportType.FREE);
            }
        };
        SerialPortManager.CurrentInfo currentInfo = sportsDatas.get(sportsDatas.size() - 1);
        System.out.println("ddddddddddddddddddddddd  SportsDataUtils   mRid  :  "+mRid);
        System.out.println("ddddddddddddddddddddddd  SportsDataUtils   sportsData  :  " + DataManager.Companion.getInstance().getGson().toJson(sportsData));
        HttpMethods.Companion.getInstance().runUploadSportInfo(
                DataManager.Companion.getInstance().getMyInfo().getUid(),
                mRid,
                mSportType.getValue(),
                Utils.getNewFloat2(currentInfo.distance / 1000f),
                Utils.getNewFloat(currentInfo.power * 0.1f),
                String.valueOf(currentInfo.count * 60 / currentInfo.time),
                String.valueOf(currentInfo.heart),
                Utils.getNewFloat(currentInfo.power * 0.1f),
                Utils.getNewFloat(currentInfo.kcal * 0.1f),
                currentInfo.time,
                DataManager.Companion.getInstance().getGson().toJson(sportsData), isEnd ? 1 : 0,
                observer);
//        else {
//            mLastUploadTime = mLastTime;
//            if (mMateId <= 0) {
//                randUser();
//                return;
//            }
//            HttpMethods.Companion.getInstance().uploadSportInfo(
//                    DataManager.Companion.getInstance().getMyInfo().getUid(),
//                    mRid, mVid, mSportType.getValue(), mScore, mMateId, Utils.getNewFloat2(currentInfo.distance / 1000f),
//                    Utils.getNewFloat(currentInfo.power * 0.1f), String.valueOf(currentInfo.count * 60 / currentInfo.time), String.valueOf(currentInfo.heart),
//                    Utils.getNewFloat(currentInfo.power * 0.1f), Utils.getNewFloat(currentInfo.kcal * 0.1f), currentInfo.time,
//                    DataManager.Companion.getInstance().getGson().toJson(sportsData), isEnd ? 1 : 0,
//                    observer);
//        }

    }

    public void closeDisposable(){
        if(disposable != null){
            disposable.dispose();
            disposable = null;
        }
    }

    public static float mean(ArrayList<Float> speeds) {
        float sum = 0;
        for (float v : speeds) {
            sum = sum + v;
        }
        return sum / speeds.size();
    }

    /**
     * 清空集合内元素
     */
    public void clearList(){
        speeds.clear();
        drag.clear();
        watts.clear();
        reta.clear();
    }

}
